package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.config.Result;
import com.example.service.UserService;
import com.example.pojo.MsslyyCart;
import com.example.service.MsslyyCartService;
import com.example.pojo.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/msslyyCart")
@Api(tags = "购物车表")
public class MsslyyCartController {
    @Resource
    private MsslyyCartService msslyyCartService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;

    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @ApiOperation(value = "新增购物车商品",notes = "")
    @PostMapping
    public Result<?> save(@RequestBody MsslyyCart msslyyCart) {
        msslyyCartService.save(msslyyCart);
        return Result.success();
    }

    @ApiOperation(value = "增加商品数量",notes = "")
    @PostMapping("/addCart/{userId}/{bookId}/{cartAmount}")
    public Result<?> addCart(@PathVariable Long userId,@PathVariable Long bookId,@PathVariable Integer cartAmount) {
        return Result.success(msslyyCartService.addCart(userId,bookId,cartAmount));
    }

    @ApiOperation(value = "更新购物车商品",notes = "")
    @PutMapping
    public Result<?> update(@RequestBody MsslyyCart msslyyCart) {
        msslyyCartService.updateById(msslyyCart);
        return Result.success();
    }

    @ApiOperation(value = "更新购物商品数量",notes = "")
    @PutMapping("/updateCartAmount/{userId}/{bookId}/{cartAmount}")
    public Result<?> updateCartAmount(@PathVariable Long userId,@PathVariable Long bookId,@PathVariable Integer cartAmount) {
        QueryWrapper<MsslyyCart> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<MsslyyCart> eq = queryWrapper.lambda()
                .eq(MsslyyCart::getUserId, userId)
                .eq(MsslyyCart::getBookId, bookId);
        MsslyyCart cartItem = msslyyCartService.getOne(eq);
        cartItem.setCartAmount(cartAmount);
        msslyyCartService.updateById(cartItem);
        return Result.success();
    }

    @ApiOperation(value = "删除购物车商品",notes = "")
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        msslyyCartService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/{userId}/{bookId}")
    public Result<?> delete(@PathVariable Long userId,@PathVariable Long bookId) {
        LambdaQueryWrapper<MsslyyCart> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(MsslyyCart::getUserId,userId).eq(MsslyyCart::getBookId,bookId);
        msslyyCartService.remove(queryWrapper);
        return Result.success();
    }
    @PostMapping("/delete/{list}/{userId}")
    public Result<?> delete(@PathVariable Object list,@PathVariable Long userId) {
        String s = String.valueOf(list);
        String[] ids = s.split(",");
        for (int i = 0; i < ids.length; i++) {
            QueryWrapper<MsslyyCart> queryWrapper=new QueryWrapper<>();
            LambdaQueryWrapper<MsslyyCart> eq = queryWrapper
                    .lambda()
                    .eq(MsslyyCart::getBookId, ids[i])
                    .eq(MsslyyCart::getUserId, userId);
            msslyyCartService.remove(eq);
        }


        return Result.success();
    }

    @ApiOperation(value = "根据id查询",notes = "")
    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(msslyyCartService.getById(id));
    }

    @ApiOperation(value = "查询全部",notes = "")
    @GetMapping
    public Result<?> findAll() {
        List<MsslyyCart> list = msslyyCartService.list();
        return Result.success(list);
    }

    @ApiOperation(value = "分页",notes = "")
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<MsslyyCart> query = Wrappers.<MsslyyCart>lambdaQuery().orderByDesc(MsslyyCart::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(MsslyyCart::getBookId, name);
        }
        IPage<MsslyyCart> page = msslyyCartService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

}
